package com.own.demo.geodemo;

import com.own.demo.geogrid.BoundingBoxUtil;
import com.own.demo.geogrid.UtilsGeoGrid;
import com.own.demo.utils.DateUtils;
import com.own.demo.utils.FileToStringUtils;
import com.own.demo.utils.RegionUtil;
import com.own.demo.utils.geo.PoiTypeEnums;
import com.own.demo.utils.geo.buffer.BufferBase;
import com.own.demo.utils.geo.buffer.LineBufferImpl;
import com.own.demo.utils.geo.buffer.PolygonBufferImpl;
import com.own.demo.vo.RoadInfo;
import org.junit.Test;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.opengis.geometry.BoundingBox;

import java.io.File;
import java.text.ParseException;
import java.util.*;

public class GeoGridTestRoadV3 {
    static PolygonBufferImpl polygonBuffer = new PolygonBufferImpl();
    static LineBufferImpl lineBuffer = new LineBufferImpl();
    static String[] noPoint = "112.788572,28.244334;113.593521,28.182595;113.314825,28.334820;113.325724,28.037024;112.785673,28.181760;112.783130,28.167562".split("\\;");

    @Test
    public void testGeoArea() {
        System.out.println("开始执行");

        File roadFile = new File("E:\\ownCode\\emg-geojson\\src\\test\\java\\com\\own\\demo\\geodemo\\changsha.txt");
        String geoDataRoad = FileToStringUtils.txt2String(roadFile);
        String[] adasStrRoad = geoDataRoad.split("\r\n");

        Map<String, List<RoadInfo>> dataRoadMap = new HashMap<>();
        for (int i = 1; i < adasStrRoad.length; i++) {
            RoadInfo roadInfo = new RoadInfo(adasStrRoad[i].split("\t"));
            List<RoadInfo> road = dataRoadMap.get(roadInfo.getRoadCode());
            if (road == null) {
                road = new ArrayList<>();
                dataRoadMap.put(roadInfo.getRoadCode(), road);
            }
            road.add(roadInfo);
        }


        File geoZJ = new File("E:\\ownCode\\emg-geojson\\src\\test\\java\\com\\own\\demo\\geodemo\\device.txt");
        String geoData = FileToStringUtils.txt2String(geoZJ).split("\\|")[0];
        String[] adasStr = geoData.split("\\,");
        int row = adasStr.length;
        System.out.println("行政区域围栏点数量：" + row);

        List<Double> lonList = new ArrayList(100000);
        List<Double> latList = new ArrayList(100000);

        for (int i = 0; i < row; i++) {
            String[] points = adasStr[i].split(" ");
            int pointLength = points.length;
            if (pointLength > 2) {
                System.out.println("错误采集点");
                continue;
            }

            try {
                lonList.add(Double.valueOf(points[0]));
                latList.add(Double.valueOf(points[1]));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        System.out.println("lon长度" + lonList.size());
        System.out.println("lat长度" + latList.size());

        double minLon = Collections.min(lonList);
        double maxLon = Collections.max(lonList);
        double minLat = Collections.min(latList);
        double maxLat = Collections.max(latList);
        try {
            BoundingBox boundingBox = BoundingBoxUtil.getBoundingBox(minLon, maxLon, minLat, maxLat);
            Geometry geometry = PoiTypeEnums.geometry(geoData, PoiTypeEnums.POLYGON.getCode());
            double sideLen = 0.09;//UtilsGeoGrid.getSideLen(boundingBox);
            List<Geometry> list = new UtilsGeoGrid().gridGeometryInfo(geometry, boundingBox,true,sideLen);
            List<Polygon> listPolygon = new ArrayList<>();
            int count = list.size();
            for (int i = 0; i < count; i++) {
                Polygon polygon = (Polygon) list.get(i);
                getSql(polygon, i, dataRoadMap, listPolygon);
            }

            count = listPolygon.size();
            for (Map.Entry<String, List<RoadInfo>> roadInfoEntry : dataRoadMap.entrySet()) {
                int finalCount = count;
                roadInfoEntry.getValue().forEach(a -> {
                    double lon = a.getX();
                    double lat = a.getY();
                    String points = lon + "," + lat;
                    for (int i = 0; i < finalCount; i++) {
                        Polygon polygon = listPolygon.get(i);
                        String data = polygonBuffer.gpsToString(polygon.getCoordinates());
                        if (RegionUtil.polygonCheck(points, data)) {
                            Point point = polygon.getCentroid();
                            String center = point.getX() + "," + point.getY();
                            a.setGridGps(center);
                            a.setX(point.getX());
                            a.setY(point.getY());
                            continue;
                        }
                    }
                });
            }
            System.out.println("-----");

            addRoadSQL(dataRoadMap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addRoadSQL(Map<String, List<RoadInfo>> dataRoadMap) throws ParseException {
        System.out.println("DELETE from geofence where service_id=713 and geofence_shape='polyline';");
        for (Map.Entry<String, List<RoadInfo>> roadInfoEntry : dataRoadMap.entrySet()) {
            StringBuilder stringBuilderBuffer = new StringBuilder();
            roadInfoEntry.getValue().forEach(a -> {
                double lat = a.getX();
                double lon = a.getY();
                stringBuilderBuffer.append(lat).append(",").append(lon).append(";");
            });
            String data = stringBuilderBuffer.deleteCharAt(stringBuilderBuffer.length() - 1).toString();
            String gps = lineBuffer.geometryInfo(data,0D);
            String sql = "INSERT INTO `geofence` (" +
                    "`service_id`," +
                    "`ak`," +
                    "`cert_info_id`," +
                    "`geofence_name`," +
                    "`geofence_shape`," +
                    "`coordinates_buffer`," +
                    "`end_time`," +
                    "`start_time`," +
                    "`deleted`," +
                    "`group_id`," +
                    "`fence_create_type`," +
                    "`coordinates`," +
                    "`center`," +
                    "`radius`," +
                    "`poi_id`," +
                    "`bounds`," +
                    "`buffer`," +
                    "`judge_type`," +
                    "`status`," +
                    "`audit_info`," +
                    "`money`," +
                    "`audit_time`," +
                    "`audit_user_id`," +
                    "`create_time`," +
                    "`warning_count`," +
                    "`geometry_info`," +
                    "`adcode`," +
                    "`max_geometry` " +
                    ")" +
                    "VALUES" +
                    "(" +
                    "" +
                    "713," +
                    "'FD1635824265606119417A4631F30DB04342A86E12D485369E64NSZETCMM7254'," +
                    "254," +
                    "'" + roadInfoEntry.getKey() + "'," +
                    "'polyline'," +
                    "'" + data + "'," +
                    "NULL," +
                    "NULL," +
                    "0," +
                    "NULL," +
                    "'0'," +
                    "'" + data + "'," +
                    "NULL," +
                    "NULL," +
                    "NULL," +
                    "NULL," +
                    "0.00," +
                    "NULL," +
                    "0," +
                    "NULL," +
                    "0.00," +
                    "NULL," +
                    "NULL," +
                    "'" + DateUtils.parseDateToStr(new Date()) + "'," +
                    "0," +
                    "ST_GeomFromText ( '" + gps + "' )," +
                    "NULL," +
                    "NULL " +
                    ");";
            System.out.println(sql);
        }

    }

    public static void getSql(Polygon polygon, int h, Map<String, List<RoadInfo>> dataRoadMap, List<Polygon> listPolygon) {
        String data = polygonBuffer.gpsToString(polygon.getCoordinates());
        for (int i = 0; i < noPoint.length; i++) {
            String point = noPoint[i];
            if (RegionUtil.polygonCheck(point, data)) {
                return;
            }
        }
        listPolygon.add(polygon);
    }
}
